/**
* Projet Chat System
* 
* @author Yann MBOUNGOU et Jean-Christophe VENDOME
* ELEVES INGENIEUR - 4e Année - Informatique et Réseaux
* INSA TOULOUSE, Dept. GEI - 2014 - 2015
*/
package NI;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public final class TCPServer extends Thread{
    private static InputStream in;
    private ServerSocket server;
    private Socket client;
    private File f;
    private static ChatNI chatni;
    private String user;
    private int port;
    private FileOutputStream out;
    private BufferedOutputStream bout;
    static int bytesRead,current=0;
   
   
    public TCPServer(int port,String user,String fname,ChatNI chatni) 
    {
        this.port=port;
        this.user=user;
        //this.f=new File(System.getProperty("C:\\Users\\UT\\Desktop")+"\\"+fname);
        this.f=new File(fname);
        TCPServer.chatni=chatni;        
    }
   
    /*************************LE RUN*************************/
    @Override
    public void run()
    {
        try
        {
            System.out.println("Serveur TCP sur le port "+port+"...");
            server=new ServerSocket(port);
            client=server.accept();
            runAppli(client);
        }
        catch(Exception e)
        {
            System.err.println("Arret du serveur.");
            System.err.println(e);
        }
    }
    /*************************FIN RUN************************/
    public void runAppli(Socket client) throws IOException
    {
        System.out.println("Connexion depuis "+client.getInetAddress()+":"+client.getPort()+"...");
        initStreams(client);
    }
    ///////////////////////////////////////////////
    ///////////////////////////////////////////////
    public void initStreams(Socket s) throws IOException
    {
         try
        {          
                client=s;
                byte[] buf = new byte[client.getReceiveBufferSize()];
                in= client.getInputStream();                
                out = new FileOutputStream(new File("Received_"+f.getName()));
                bout = new BufferedOutputStream(out);
                while((bytesRead= in.read(buf)) > 0)
                {
                    bout.write(buf, 0 , bytesRead);
                }                
                bout.flush();         
                bout.close();
                in.close();
                client.close();
                server.close();
                TCPServer.chatni.receivedfile(user);
        }
        catch (IOException e) 
        {
                System.err.println("!! IOException TCPServer="+e);
        }
    }
    ///////////////////////////////////////////////

   
}

